<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>VIP透支管理</p>
		</header>

		<!-- 权限检查提示 -->
		<div v-if="!isVipUser" class="permission-denied">
			<i class="fa fa-lock"></i>
			<h3>权限不足</h3>
			<p>仅VIP用户可使用透支功能</p>
			<button @click="goBack">返回钱包首页</button>
		</div>

		<!-- 透支管理内容 -->
		<div v-else>
			<!-- 透支额度信息 -->
			<div class="overdraft-info">
				<h3>透支额度信息</h3>
				<div class="quota-display">
					<div class="quota-item">
						<span class="label">总额度</span>
						<span class="value">¥{{ overdraftLimit.toFixed(2) }}</span>
					</div>
					<div class="quota-item">
						<span class="label">已使用</span>
						<span class="value used">¥{{ usedOverdraft.toFixed(2) }}</span>
					</div>
					<div class="quota-item">
						<span class="label">剩余额度</span>
						<span class="value available">¥{{ remainingOverdraft.toFixed(2) }}</span>
					</div>
				</div>
			</div>

			<!-- 待还款信息 -->
			<div class="repayment-info" v-if="unpaidAmount > 0">
				<h3>待还款信息</h3>
				<div class="repayment-details">
					<div class="detail-item">
						<span>未还金额:</span>
						<span class="amount">¥{{ unpaidAmount.toFixed(2) }}</span>
					</div>
					<div class="detail-item">
						<span>还款截止日期:</span>
						<span class="deadline" :class="{ 'overdue': isOverdue }">{{ formatDate(repaymentDeadline) }}</span>
					</div>
					<div class="detail-item" v-if="isOverdue">
						<span>逾期利息:</span>
						<span class="interest">¥{{ overdueInterest.toFixed(2) }} ({{ interestRate }}%/天)</span>
					</div>
				</div>

				<!-- 还款操作 -->
				<div class="repayment-action">
					<div class="repayment-form">
						<div class="amount-input">
							<label>还款金额</label>
							<div class="input-group">
								<span class="currency">¥</span>
								<input
									type="number"
									v-model="repaymentAmount"
									placeholder="请输入还款金额"
									min="0.01"
									:max="unpaidAmount"
									step="0.01"
								/>
							</div>
							<div class="quick-amounts">
								<button @click="setRepaymentAmount(unpaidAmount)">全额还款</button>
								<button @click="setRepaymentAmount(Math.min(100, unpaidAmount))">还款100元</button>
								<button @click="setRepaymentAmount(Math.min(50, unpaidAmount))">还款50元</button>
							</div>
						</div>
					</div>

					<button
						class="repayment-btn"
						@click="confirmRepayment"
						:disabled="isProcessing || !isValidRepaymentAmount"
					>
						<span v-if="isProcessing">处理中...</span>
						<span v-else>确认还款</span>
					</button>
				</div>
			</div>

			<!-- 无待还款提示 -->
			<div class="no-repayment" v-else>
				<i class="fa fa-check-circle"></i>
				<h3>恭喜您</h3>
				<p>当前无待还款金额</p>
				<p class="tip">透支额度可正常使用</p>
			</div>

			<!-- 透支规则说明 -->
			<div class="rules-section">
				<h3>透支规则说明</h3>
				<div class="rules-content">
					<p>• 透支额度仅限VIP用户使用，固定额度为1000元</p>
					<p>• 透支资金需在{{ repaymentPeriod }}天内还清</p>
					<p>• 逾期将收取{{ interestRate }}%/天的利息</p>
					<p>• 还款时优先偿还利息和手续费</p>
					<p>• 严重逾期可能影响VIP资格</p>
				</div>
			</div>
		</div>

		<!-- 加载状态 -->
		<div v-if="isLoading" class="loading">
			<p>加载中...</p>
		</div>

		<!-- 错误提示 -->
		<div v-if="errorMsg" class="error-msg">
			<p>{{ errorMsg }}</p>
			<button @click="loadOverdraftData">重试</button>
		</div>

		<!-- 返回按钮 -->
		<div class="back-button" v-if="isVipUser">
			<button @click="goBack">返回钱包首页</button>
		</div>

		<!-- 底部菜单 -->
		<Footer v-if="isVipUser"></Footer>
	</div>
</template>

<script>
import Footer from '../components/Footer.vue';
import axios from 'axios';

export default {
	name: 'WalletOverdraft',
	components: {
		Footer
	},
	data() {
		return {
			isVipUser: false,
			overdraftLimit: 0,
			usedOverdraft: 0,
			unpaidAmount: 0,
			repaymentDeadline: null,
			repaymentAmount: '',
			isLoading: false,
			isProcessing: false,
			errorMsg: '',
			repaymentPeriod: 30, // 还款周期（天）
			interestRate: 0.5 // 逾期利率（%/天）
		};
	},
	computed: {
		remainingOverdraft() {
			return Math.max(0, this.overdraftLimit - this.usedOverdraft);
		},
		isOverdue() {
			if (!this.repaymentDeadline) return false;
			return new Date() > new Date(this.repaymentDeadline);
		},
		overdueInterest() {
			if (!this.isOverdue || !this.repaymentDeadline) return 0;
			const overdueDays = Math.ceil((new Date() - new Date(this.repaymentDeadline)) / (1000 * 60 * 60 * 24));
			return this.unpaidAmount * (this.interestRate / 100) * Math.max(0, overdueDays);
		},
		isValidRepaymentAmount() {
			const amount = parseFloat(this.repaymentAmount) || 0;
			return amount > 0 && amount <= this.unpaidAmount;
		}
	},
	methods: {
		async loadOverdraftData() {
			this.isLoading = true;
			this.errorMsg = '';
			try {
				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				// 获取钱包余额信息
				const response = await axios.get('wallet/balance', {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				});

				if (response.data.success && (response.data.code === 200 || response.data.code === 0)) {
					const walletData = response.data.data;
					// 检查用户是否为VIP（优先使用isVip或vipUser字段，如果没有则检查权限）
					this.isVipUser = walletData.isVip || 
					                  walletData.vipUser || 
					                  walletData.user?.authorities?.some(auth => auth.name === 'VIP') || 
					                  false;

					if (!this.isVipUser) {
						return;
					}

					// VIP用户固定透支额度为1000元
					this.overdraftLimit = 1000;

					// 模拟透支使用情况，实际应从后端获取
					// 这里暂时用模拟数据，实际需要后端提供透支使用详情接口
					this.usedOverdraft = Math.max(0, this.overdraftLimit - walletData.balance);
					this.unpaidAmount = Math.max(0, this.usedOverdraft);

					// 设置还款截止日期（假设从透支发生之日起30天）
					if (this.unpaidAmount > 0) {
						this.repaymentDeadline = new Date();
						this.repaymentDeadline.setDate(this.repaymentDeadline.getDate() + this.repaymentPeriod);
					} else {
						this.repaymentDeadline = null;
					}
				} else {
					this.errorMsg = response.data.message || '获取透支信息失败';
				}
			} catch (error) {
				this.errorMsg = '网络错误，请重试';
			} finally {
				this.isLoading = false;
			}
		},
		setRepaymentAmount(amount) {
			this.repaymentAmount = amount.toFixed(2);
		},
		async confirmRepayment() {
			if (!this.isValidRepaymentAmount) return;

			this.isProcessing = true;
			this.errorMsg = '';

			try {
				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				// 这里应该调用还款接口，暂时用充值接口模拟（实际需要后端提供还款接口）
				// 还款逻辑：使用钱包余额还款
				const response = await axios.post('wallet/recharge', null, {
					headers: {
						'Authorization': `Bearer ${token}`
					},
					params: {
						amount: -parseFloat(this.repaymentAmount), // 负数表示还款
						remark: '透支还款'
					},
					timeout: 10000
				});

				if (response.data.success && (response.data.code === 200 || response.data.code === 0)) {
					// 还款成功，刷新数据
					this.repaymentAmount = '';
					await this.loadOverdraftData();
					alert('还款成功！');
				} else {
					this.errorMsg = response.data.message || '还款失败';
				}
			} catch (error) {
				this.errorMsg = '网络错误，请重试';
			} finally {
				this.isProcessing = false;
			}
		},
		formatDate(date) {
			if (!date) return '';
			return new Date(date).toLocaleDateString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit'
			});
		},
		goBack() {
			this.$router.push('/wallet');
		}
	},
	mounted() {
		this.loadOverdraftData();
	}
};
</script>

<style scoped>
.wrapper {
	padding-bottom: 60px;
	min-height: 100vh;
	background-color: #f5f5f5;
}

header {
	background-color: #0097ff;
	color: #fff;
	padding: 4vw;
	text-align: center;
}

header p {
	margin: 0;
	font-size: 4.5vw;
	font-weight: 500;
}

/* 权限不足提示 */
.permission-denied {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 6vw 4vw;
	text-align: center;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.permission-denied i {
	font-size: 8vw;
	color: #ff4d4f;
	margin-bottom: 3vw;
}

.permission-denied h3 {
	margin: 0 0 2vw 0;
	color: #333;
	font-size: 4.5vw;
}

.permission-denied p {
	margin: 0 0 4vw 0;
	color: #666;
	font-size: 3.5vw;
}

.permission-denied button {
	background-color: #0097ff;
	color: #fff;
	border: none;
	border-radius: 2vw;
	padding: 3vw 6vw;
	font-size: 4vw;
	cursor: pointer;
}

.permission-denied button:hover {
	background-color: #007acc;
}

/* 透支额度信息 */
.overdraft-info {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.overdraft-info h3 {
	margin: 0 0 3vw 0;
	font-size: 4vw;
	color: #333;
	font-weight: 500;
}

.quota-display {
	display: flex;
	justify-content: space-between;
}

.quota-item {
	text-align: center;
	flex: 1;
}

.quota-item .label {
	display: block;
	font-size: 3vw;
	color: #666;
	margin-bottom: 1vw;
}

.quota-item .value {
	display: block;
	font-size: 5vw;
	font-weight: bold;
	color: #333;
}

.quota-item .value.used {
	color: #ff4d4f;
}

.quota-item .value.available {
	color: #52c41a;
}

/* 待还款信息 */
.repayment-info {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.repayment-info h3 {
	margin: 0 0 3vw 0;
	font-size: 4vw;
	color: #333;
	font-weight: 500;
}

.repayment-details {
	background-color: #fff3cd;
	border: 1px solid #ffeaa7;
	border-radius: 1vw;
	padding: 3vw;
	margin-bottom: 4vw;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 2vw;
	font-size: 3.5vw;
	color: #856404;
}

.detail-item:last-child {
	margin-bottom: 0;
}

.amount {
	font-weight: bold;
	font-size: 4vw;
}

.deadline {
	font-weight: 500;
}

.deadline.overdue {
	color: #ff4d4f;
}

.interest {
	color: #ff4d4f;
	font-weight: 500;
}

/* 还款操作 */
.repayment-action {
	margin-top: 4vw;
}

.amount-input label {
	display: block;
	margin-bottom: 2vw;
	font-size: 3.5vw;
	color: #333;
	font-weight: 500;
}

.input-group {
	display: flex;
	align-items: center;
	border: 1px solid #ddd;
	border-radius: 1vw;
	padding: 3vw;
	margin-bottom: 3vw;
}

.currency {
	font-size: 4vw;
	color: #666;
	margin-right: 2vw;
	font-weight: 500;
}

.input-group input {
	flex: 1;
	border: none;
	outline: none;
	font-size: 4vw;
	color: #333;
}

.quick-amounts {
	display: flex;
	flex-wrap: wrap;
	gap: 2vw;
	margin-bottom: 3vw;
}

.quick-amounts button {
	flex: 1;
	min-width: 20vw;
	padding: 2vw;
	border: 1px solid #ddd;
	border-radius: 1vw;
	background-color: #fff;
	color: #666;
	font-size: 3vw;
	cursor: pointer;
	transition: all 0.3s;
}

.quick-amounts button:hover {
	border-color: #0097ff;
	color: #0097ff;
	background-color: #f0f8ff;
}

.repayment-btn {
	width: 100%;
	background-color: #0097ff;
	color: #fff;
	border: none;
	border-radius: 2vw;
	padding: 3vw;
	font-size: 4vw;
	cursor: pointer;
	transition: all 0.3s;
}

.repayment-btn:hover:not(:disabled) {
	background-color: #007acc;
}

.repayment-btn:disabled {
	background-color: #ccc;
	cursor: not-allowed;
}

/* 无待还款提示 */
.no-repayment {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 6vw 4vw;
	text-align: center;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.no-repayment i {
	font-size: 8vw;
	color: #52c41a;
	margin-bottom: 3vw;
}

.no-repayment h3 {
	margin: 0 0 2vw 0;
	color: #333;
	font-size: 4.5vw;
}

.no-repayment p {
	margin: 0 0 1vw 0;
	color: #666;
	font-size: 3.5vw;
}

.no-repayment .tip {
	color: #52c41a;
	font-size: 3vw;
}

/* 规则说明 */
.rules-section {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.rules-section h3 {
	margin: 0 0 3vw 0;
	font-size: 4vw;
	color: #333;
	font-weight: 500;
}

.rules-content p {
	margin: 0 0 1vw 0;
	font-size: 3.5vw;
	color: #666;
	line-height: 1.5;
}

.rules-content p:last-child {
	margin-bottom: 0;
}

/* 加载和错误状态 */
.loading {
	text-align: center;
	padding: 6vw;
	color: #666;
	font-size: 4vw;
}

.error-msg {
	background-color: #fff;
	margin: 3vw;
	border-radius: 2vw;
	padding: 4vw;
	text-align: center;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.error-msg p {
	margin: 0 0 3vw 0;
	color: #ff4d4f;
	font-size: 3.5vw;
}

.error-msg button {
	background-color: #0097ff;
	color: #fff;
	border: none;
	border-radius: 1vw;
	padding: 2vw 4vw;
	font-size: 3.5vw;
	cursor: pointer;
}

.error-msg button:hover {
	background-color: #007acc;
}

/* 返回按钮 */
.back-button {
	margin: 3vw;
}

.back-button button {
	width: 100%;
	background-color: #f5f5f5;
	color: #666;
	border: none;
	border-radius: 2vw;
	padding: 3vw;
	font-size: 4vw;
	cursor: pointer;
}

.back-button button:hover {
	background-color: #e9ecef;
}
</style>
